package com.mycode.chapter01;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class Response {

    private static final int BUFFER_SIZE = 1024;
    private OutputStream outputStream;
    private Request request;
    
    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public void sendStaticResource() throws IOException {
        byte[] bytes = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        try {
            File file = new File(HttpServer.WEB_ROOT, request.getUri());
            if (file.exists() && file.isFile()) {
                fis = new FileInputStream(file);
                int count = 0;
                while (count == 0) {
                    count = fis.available();
                }
                String successMessage = "HTTP/1.1 200 OK \n" +
                        "Content-type:text/html \n" +
                        "Content-Length: " + count + " \n" +
                        "\r\n";

                outputStream.write(successMessage.getBytes(StandardCharsets.UTF_8));
                int ch = fis.read(bytes, 0, BUFFER_SIZE);
                while (ch!=-1) {
                    outputStream.write(bytes, 0, ch);
                    ch = fis.read(bytes, 0, BUFFER_SIZE);
                }
            }
            else {
                // file not found
                String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
                        "Content-Type: text/html\r\n" +
                        "Content-Length: 23\r\n" +
                        "\r\n" +
                        "<h1>File Not Found</h1>";
                outputStream.write(errorMessage.getBytes());
            }
        }
        catch (Exception e) {
            // thrown if cannot instantiate a File object
            System.out.println(e.toString() );
        }
        finally {
            if (fis!=null) {
                fis.close();
            }
        }
    }
}
